<?php

namespace app\api\controller;

use app\admin\model\Maintenance;
use app\common\controller\Api;
use app\common\model\Order;
use app\common\model\OrderInfo;
use think\Log;
use Yansongda\Pay\Exceptions\GatewayException;
use Yansongda\Pay\Exceptions\InvalidArgumentException;
use Yansongda\Pay\Exceptions\InvalidSignException;
use Yansongda\Pay\Pay as ysPay;
use function EasyWeChat\Kernel\Support\generate_sign;

/**
 * 首页接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $config = [
        'appid' => 'wx310288c45d4d1251', // APP APPID
        'app_id' => 'wx310288c45d4d1251', // 公众号 APPID
        'miniapp_id' => 'wx310288c45d4d1251', // 小程序 APPID
        'mch_id' => '1699424716',
        'key' => 'j6qpsqrz8onhiaeax47cdg85yvo10zgo',
        'notify_url' => 'https://car.3llh.com/api/pay/notify',
        'cert_client' => ROOT_PATH . '/public/cert/apiclient_cert.pem', // optional, 退款，红包等情况时需要用到
        'cert_key' => ROOT_PATH . '/public/cert/apiclient_key.pem',// optional, 退款，红包等情况时需要用到
        'log' => [ // optional
            'file' => './logs/wechat.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        'mode' => 'normal',
    ];

    /**
     * 首页
     *
     */
    public function pay()
    {
        $order_id = input('order_id');
        $orderModel = new Order();
        $orderInfo = $orderModel->where('id', $order_id)->find();
        if (!$orderInfo) {
            $this->error('订单不存在');
        }
//        if ($orderInfo['status'] != 1){
//            $this->error('订单已支付');
//        }
        $openid = $this->request->header('openid');

        $order = [
            'out_trade_no' => $orderInfo['order_sn'],
            'body' => $orderInfo['vehicle_name'],
            'total_fee' => $orderInfo['price'] * 100,
            'openid' => $openid,
        ];
        $result = ysPay::wechat($this->config)->miniapp($order);
        $this->success('请求成功', $result);
    }

    public function createMaintenance()
    {
        //授权书 图片链接 https://image1.3llh.com/uploads/20250603/FnTLuT5KEjHBqNVCVt-UAiuX0kxf.png
        $vin = input('vin');
        $type = input('type');
        $signature_image = input('signature_image');
        $driving_license_image = input('driving_license_image');
        if (!$vin || !$driving_license_image) {
            $this->error('请完善信息');
        }
        if ($type == 1 && !$signature_image){
            $this->error('请填写签名图片');
        }
        $openid = $this->request->header('openid');
        $amount = 0.01;
        $body = '维保查询';
        switch ($type) {
            case '1':
                $amount = 35;
                $body = '事故查询';
                break;
            case '2':
                $amount = 35;
                $body = '维保查询';
                break;
            case '3':
                $amount = 40;
                $body = '动力电池查询';
                break;
        }
        $orderDetail = [
            'user_id' => $this->auth->id,
            'vin' => $vin,
            'type' => $type,
            'signature_image' => $signature_image??'',
            'order_no' => build_order_no(),
            'amount' => $amount,
            'driving_license_image' => $driving_license_image,
            'createtime' => time(),
            'updatetime' => time()
        ];
        if ($type == 1) {
            //生成签名图片
            $Vehicle = new Vehicle();
            $orderDetail['letter_of_auth_image'] = $Vehicle->generateDoc(get_app_image_url($signature_image), $vin);
        }

        $model = new Maintenance();
        $model->save($orderDetail);

        $order = [
            'out_trade_no' => $orderDetail['order_no'],
            'body' => $body,
            'total_fee' => $orderDetail['amount'] * 100,
            'openid' => $openid,
        ];
        $config = $this->config;
        $config['notify_url'] = 'https://car.3llh.com/api/pay/notifyMaintenance';
        $result = ysPay::wechat($config)->miniapp($order);
        $this->success('请求成功', $result);
    }

    public function testPay()
    {


        $filePath = ROOT_PATH . '/public/cert/apiclient_cert.pem';

// 检查文件是否存在且可读
        if (file_exists($filePath) && is_readable($filePath)) {
            // 文件存在且可读，读取文件内容
            $content = file_get_contents($filePath);
            echo $content;
        } else {
            echo "文件不存在或不可读";
        }
        Log::log('Wechat notify');

        var_dump(ROOT_PATH);
        var_dump(__DIR__);
    }

    public function notify()
    {

        $orderInfoModel = new Order();

        $wechat = ysPay::wechat($this->config);
        try {
            $data = $wechat->verify(); // 返回 `Yansongda\Supports\Collection` 实例，可以通过 `$data->xxx` 访问服务器返回的数据。
            //以下根据自己业务进行支付校验
            $order = $orderInfoModel->where('order_sn', $data['out_trade_no'])->find();
            if (!$order || $order->status != 1) {
                //如果订单状态异常直接退出
                return $wechat->success();
            }
//            $total_fee=bcdiv($data->total_fee,100,2);
            $orderInfoModel->where('order_sn', $data->out_trade_no)->update(['status' => 2, 'pay_time' => date('Y-m-d H:i:s')]);
            Log::log('Wechat notify' . json_encode($data));
            return $wechat->success();
        } catch (\Exception $e) {
            Log::error('Wechat notify error' . $e->getMessage());
        }
        return $wechat->success();
    }

    public function notifyMaintenance()
    {

        $model = new Maintenance();

        $wechat = ysPay::wechat($this->config);
        try {
            $data = $wechat->verify(); // 返回 `Yansongda\Supports\Collection` 实例，可以通过 `$data->xxx` 访问服务器返回的数据。
            //以下根据自己业务进行支付校验
            $order = $model->where('order_no', $data['out_trade_no'])->find();
            if (!$order || $order->status != 0) {
                //如果订单状态异常直接退出
                return $wechat->success();
            }
            $expire_time = date('Y-m-d H:i:s', strtotime('+30 days'));
//            $total_fee=bcdiv($data->total_fee,100,2);
            $model->where('order_no', $data->out_trade_no)->update(['status' => 1, 'expire_time' => $expire_time]);
            Log::log('Wechat notifyMaintenance' . json_encode($data));
            return $wechat->success();
        } catch (\Exception $e) {
            Log::error('Wechat notifyMaintenance error' . $e->getMessage());
        }
        return $wechat->success();
    }

    public function refund()
    {
        $wechat = ysPay::wechat($this->config);
        $order_id = input('order_id');
        $orderInfoModel = new Order();
        $orderInfo = $orderInfoModel->where('id', $order_id)->find();
        if (!$orderInfo) {
            $this->error('订单不存在');
        }
        if (!in_array($orderInfo['status'], [2, 3, 6])) {
            $this->error('订单当前订单不可取消');
        }
        if ($orderInfo['status'] == '-1') {
            $this->error('订单已取消');
        }
        try {
            $wechat->refund([
                'out_trade_no' => $orderInfo['order_sn'],
                'out_refund_no' => time(),
                'total_fee' => $orderInfo['price'] * 100,
                'refund_fee' => $orderInfo['price'] * 100,
                'refund_desc' => $orderInfo['vehicle_name'] . '退款',
                'type' => 'miniapp',
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $orderInfoModel->where('id', $order_id)->update(['status' => '-1', 'cancel_time' => time()]);
        $this->success('请求成功', []);
    }
}
